package com.chenfan.ccp.plug.business.send;

import com.chenfan.ccp.plug.business.entity.BusinessLog;
import com.chenfan.ccp.plug.business.util.BusinessCommonsUtil;
import com.chenfan.ccp.util.start.ApplicationContextUtil;
import com.chenfan.ccp.util.tool.HttpUtil;
import com.chenfan.ccp.util.tool.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author xutong
 */
@Slf4j
public class HttpLogSender extends AbstractLogSender implements Ordered {
    @Override
    public boolean send(BusinessLog businessLog) {
        try {
            Object discoveryClient = ApplicationContextUtil.getContext().getBean(
                    Class.forName("org.springframework.cloud.client.discovery.DiscoveryClient"));
            if (discoveryClient == null) {
                return false;
            }
            Method getInstances =
                    discoveryClient.getClass().getMethod("getInstances", String.class);
            Object instances = getInstances.invoke(discoveryClient, BusinessCommonsUtil.LOG_SERVICE_NAME);
            if (instances == null || !
                    (instances instanceof List)) {
                return false;
            }
            List list = (List) instances;
            Object obj = list.get(ThreadLocalRandom.current().nextInt(list.size()));
            Field getHost = obj.getClass().getDeclaredField("host");
            getHost.setAccessible(true);
            Object host = getHost.get(obj);

            Field getPort = obj.getClass().getDeclaredField("port");
            getPort.setAccessible(true);
            Object port = getPort.get(obj);

            String result = HttpUtil.post(
                    BusinessCommonsUtil.HTTP_PROTO + host + ":" + port + "/" +
                            BusinessCommonsUtil.BUSINESS_LOG_PATH
                    , JsonUtil.obj2String(businessLog));

            if (result != null && !result.isEmpty()) {
                log.info("http={} send success result={}", BusinessCommonsUtil.BUSINESS_LOG_TOPIC, result);
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();

        }

        return false;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
